<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { postDept, putDept } from '#/api/plugin/dept';

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  showDefaultActions: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: 1,
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['status'],
      },
      fieldName: 'status',
      label: 'status',
    },
    {
      component: 'TreeSelect',
      fieldName: 'parent_id',
      label: '上级部门',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '部门名称',
      rules: 'required',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'principal',
      label: '部门负责人',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'phone',
      label: '部门手机号',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'email',
      label: '部门邮箱',
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  async onConfirm() {
    await BasicFormApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      if (values?.form) {
        BasicFormApi.setValues(values.form);
      }
      BasicFormApi.updateSchema([
        {
          componentProps: {
            treeData: values.dept_list,
            class: 'w-3/5',
            fieldNames: {
              value: 'id',
              key: 'id',
              label: 'name',
              children: 'children',
            },
          },
          fieldName: 'parent_id',
        },
      ]);
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  if (values.id) {
    const { msg } = await putDept(values);
    showMsg(msg);
  } else {
    const { msg } = await postDept(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <BasicForm />
  </Modal>
</template>

<style lang="scss" scoped></style>
